"""
系统管理相关的API路由
包含系统状态、配置管理、监控等接口
"""

from fastapi import APIRouter, Depends, HTTPException, status
from typing import Dict, Any, Optional
from datetime import datetime

from ....core.config import config
from ....agents.agent_manager import agent_manager
from ..models import *
from ..dependencies import common_dependencies, get_request_logger

router = APIRouter(prefix="/api/v1/system", tags=["System"])


@router.get("/config", response_model=Dict[str, Any])
async def get_system_config(
    deps: Dict[str, Any] = Depends(common_dependencies)
):
    """获取系统配置"""
    try:
        # 获取核心配置（隐藏敏感信息）
        safe_config = {
            "retrieval": config.get("retrieval", {}),
            "agents": {
                "max_concurrent_tasks": config.get("agents.max_concurrent_tasks", 10),
                "task_timeout": config.get("agents.task_timeout", 300)
            },
            "services": {
                "api": {
                    "host": config.get("services.api.host", "0.0.0.0"),
                    "port": config.get("services.api.port", 8000)
                }
            }
        }
        
        return safe_config
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to get system config: {str(e)}"
        )


@router.put("/config")
async def update_system_config(
    request: UpdateConfigRequest,
    deps: Dict[str, Any] = Depends(common_dependencies)
):
    """更新系统配置"""
    try:
        if request.config_type == "retrieval":
            # 更新检索配置
            config.update((f"retrieval.{key}", value) for key, value in request.config_data.items())
            
        elif request.config_type == "agent":
            # 更新智能体配置
            config.update((f"agents.{key}", value) for key, value in request.config_data.items())
            
        elif request.config_type == "performance":
            # 更新性能配置
            config.update((f"performance.{key}", value) for key, value in request.config_data.items())
        
        return {"message": f"Configuration '{request.config_type}' updated successfully"}
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to update config: {str(e)}"
        )


@router.get("/agents/status")
async def get_agents_status(
    deps: Dict[str, Any] = Depends(common_dependencies)
):
    """获取智能体状态"""
    try:
        orchestrator = agent_manager.get_orchestrator()
        specialists = agent_manager.get_all_specialists()
        
        status_info = {
            "orchestrator": {
                "available": orchestrator is not None,
                "running_tasks": len(orchestrator.running_tasks) if orchestrator else 0,
                "completed_tasks": orchestrator.completed_tasks if orchestrator else 0
            },
            "specialists": {}
        }
        
        for name, specialist in specialists.items():
            status_info["specialists"][name] = {
                "available": specialist is not None,
                "active": getattr(specialist, 'is_active', False)
            }
        
        return status_info
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to get agents status: {str(e)}"
        )


@router.post("/agents/restart")
async def restart_agents(
    deps: Dict[str, Any] = Depends(common_dependencies)
):
    """重启智能体系统"""
    try:
        # 临时实现 - lightrag开发中
        # await agent_manager.shutdown()
        # await agent_manager.initialize()
        
        return {"message": "Agents system restart skipped (lightrag in development)"}
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to restart agents: {str(e)}"
        )


@router.get("/monitoring", response_model=MonitoringResponse)
async def get_monitoring_data(
    deps: Dict[str, Any] = Depends(common_dependencies),
    logger = Depends(get_request_logger)
):
    """获取监控数据"""
    try:
        # 获取使用统计
        stats = await logger.get_stats()
        usage_stats = UsageStats(
            total_requests=stats["total_requests"],
            successful_requests=stats["total_requests"] - stats["error_count"],
            failed_requests=stats["error_count"],
            average_response_time=stats["average_response_time"]
        )
        
        # 获取性能指标（简化版本）- 临时实现
        # orchestrator = agent_manager.get_orchestrator()
        performance_metrics = PerformanceMetrics(
            active_tasks=0,  # lightrag开发中
            queue_size=0
        )
        
        # 获取系统健康状态 - 临时实现
        # health_status = await agent_manager.health_check()
        system_health = "healthy"  # 临时状态
        
        return MonitoringResponse(
            usage_stats=usage_stats,
            performance_metrics=performance_metrics,
            system_health=system_health,
            timestamp=datetime.now()
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to get monitoring data: {str(e)}"
        )


@router.post("/cache/clear")
async def clear_cache(
    cache_type: Optional[str] = "all",
    deps: Dict[str, Any] = Depends(common_dependencies)
):
    """清除缓存"""
    try:
        if cache_type == "all" or cache_type == "vector":
            # 清除向量缓存（如果存在）
            pass
            
        if cache_type == "all" or cache_type == "response":
            # 清除响应缓存
            from ..dependencies import simple_cache
            simple_cache.cache.clear()
        
        return {"message": f"Cache '{cache_type}' cleared successfully"}
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to clear cache: {str(e)}"
        )


@router.get("/logs/stats")
async def get_log_stats(
    deps: Dict[str, Any] = Depends(common_dependencies),
    logger = Depends(get_request_logger)
):
    """获取日志统计"""
    try:
        stats = await logger.get_stats()
        return {
            "api_stats": stats,
            "timestamp": datetime.now().isoformat()
        }
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to get log stats: {str(e)}"
        )


@router.post("/experimental/feature")
async def experimental_feature(
    request: ExperimentalFeatureRequest,
    deps: Dict[str, Any] = Depends(common_dependencies)
):
    """实验性功能接口"""
    try:
        start_time = datetime.now()
        warnings = []
        
        # 根据功能名称执行不同的实验性功能
        if request.feature_name == "performance_benchmark":
            result = await _run_performance_benchmark(request.parameters)
            
        elif request.feature_name == "model_comparison":
            result = await _run_model_comparison(request.parameters)
            
        elif request.feature_name == "advanced_analytics":
            result = await _run_advanced_analytics(request.parameters)
            
        else:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Unknown experimental feature: {request.feature_name}"
            )
        
        execution_time = (datetime.now() - start_time).total_seconds()
        
        return ExperimentalFeatureResponse(
            feature_name=request.feature_name,
            result=result,
            execution_time=execution_time,
            warnings=warnings,
            timestamp=datetime.now()
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Experimental feature failed: {str(e)}"
        )

# ================================
# 辅助函数
# ================================

async def _run_performance_benchmark(parameters: Dict[str, Any]) -> Dict[str, Any]:
    """运行性能基准测试"""
    return {
        "benchmark_type": "system_performance",
        "metrics": {
            "avg_query_time": 0.5,
            "throughput": 100,
            "memory_usage": "512MB"
        },
        "status": "completed"
    }


async def _run_model_comparison(parameters: Dict[str, Any]) -> Dict[str, Any]:
    """运行模型比较分析"""
    return {
        "comparison_type": "model_performance",
        "models_compared": parameters.get("models", ["default"]),
        "results": {
            "accuracy": 0.85,
            "speed": 0.8,
            "resource_usage": 0.7
        },
        "recommendation": "Use model A for better accuracy"
    }


async def _run_advanced_analytics(parameters: Dict[str, Any]) -> Dict[str, Any]:
    """运行高级分析"""
    return {
        "analytics_type": "advanced_insights",
        "insights": [
            "High demand for Python developers",
            "Remote work preferences increasing",
            "AI/ML skills in high demand"
        ],
        "confidence_score": 0.9
    }
